package com.jf.docsify.modules.document;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import com.jf.docsify.common.utils.GitServerUtil;
import com.jf.docsify.common.utils.Resp;
import com.jf.docsify.config.DocsifyConfig;
import com.jf.docsify.modules.model.Organization;
import com.jf.docsify.modules.model.Settings;
import com.jf.docsify.modules.model.SysUser;
import com.jf.docsify.modules.orgz.OrganizationService;
import com.jfinal.aop.Inject;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Page;

/**
 * Description: 文档控制层
 *
 * @author chenwr
 * @version 1.0
 *
 * <pre>
 * 修改记录:
 * 修改后版本           修改人       修改日期         修改内容
 * 2022/7/25.1       chenwr    2022/7/25           Create
 * </pre>
 * @date 2022/7/25
 */
@Path("/docs")
public class DocController extends Controller {

    @Inject
    DocService docService;

    @Inject
    OrganizationService organizationService;

    @ActionKey("/docs/index")
    public void index() {
        String requestURI = getRequest().getRequestURI();
        String[] split = requestURI.replaceFirst("/docs/index/", "").split("/");
        if (split.length > 1) {
            String docId = split[1];
            Settings docSetting = docService.findDocSetting(docId);
            if (docSetting != null) {
                setAttr("st", docSetting);
            }
            String gitFilePath = DocsifyConfig.defaultPath + File.separator + DocsifyConfig.gitDefaultFolderName
                    + File.separator + docSetting.getDocOrgPath() + File.separator + docSetting.getEnName();
            SysUser user = getAttr("user");
            GitServerUtil.pullMaster(gitFilePath, user.getUserName(), user.getPassword());
        }
        render("index.html");
    }

    public void translate() throws UnsupportedEncodingException {
        Map<String, String> queryParams = new HashMap<>();
        queryParams.put("q", URLDecoder.decode(getPara(0), "UTF-8"));
        String jsonStr = HttpKit.get("https://gitee.com/search/translate", queryParams);
        Map<String, String> res = JsonKit.parse(jsonStr, Map.class);
        Resp.success(res.get("result")).done(this);
    }

    @ActionKey("/docs/docList")
    public void docList() {
        String organizationId = getPara(0);
        String pageSize = getPara("pageSize");
        String currentPage = getPara("currentPage");
        HttpServletRequest request = getRequest();
        String requestURL = request.getRequestURL().toString();
        String requestURI = request.getRequestURI();
        requestURL = requestURL.replace(requestURI, "/git/");
        Page<Settings> settingsPage = docService.docList(organizationId, currentPage, pageSize);
        List<Settings> list = settingsPage.getList();
        if (CollectionUtils.isNotEmpty(list)) {
            String finalRequestURL = requestURL;
            list.stream().forEach(settings -> {
                String enName = settings.getEnName();
                String docOrgPath = settings.getDocOrgPath();
                settings.setGitUrl(finalRequestURL + docOrgPath + "/" + enName + ".git");
                settings.setCreateTimeFormat(DateFormatUtils.format(settings.getCreateTime(), "yyyy-MM-dd HH:mm"));
            });
        }
        Resp.success(settingsPage).done(this);
    }

    public void saveDocSetting() {
        String rawData = getRawData();
        Settings settings = JsonKit.parse(rawData, Settings.class);
        SysUser user = getAttr("user");
        HttpServletRequest request = getRequest();
        String requestURL = request.getRequestURL().toString();
        String requestURI = request.getRequestURI();
        requestURL = requestURL.replace(requestURI, "/git");
        boolean settingSaveFlag = docService.saveSetting(settings, user.getUserName(), user.getPassword(), requestURL);
        Resp.resp(settingSaveFlag).done(this);
    }

    public void deleteDocSetting() {
        String id = getPara(0);
        boolean settingDeleteFlag = docService.deleteDocSetting(id);
        Resp.resp(settingDeleteFlag).done(this);
    }

    public void findDocSetting() {
        String id = getPara(0);
        Settings docSetting = docService.findDocSetting(id);
        Resp.success(docSetting).done(this);
    }

    @ActionKey("/docs/mdRoute")
    public void mdRoute() {
        String path = getPara("path");
        String[] split = path.replaceFirst("/docs/index/", "").split("/");
        List<String> mdPath = new ArrayList<>();
        List<String> ignoreMdFile = new ArrayList<>();
        ignoreMdFile.add("README.md");
        ignoreMdFile.add("_coverpage.md");
        ignoreMdFile.add("_navbar.md");
        ignoreMdFile.add("_sidebar.md");
        String currentFileName = split[split.length - 1];
        boolean ignore = ignoreMdFile.contains(currentFileName);
        for (int i = 0; i < split.length; i++) {
            if (i == 0) {
                continue;
            }
            if (i == 1) {
                Settings docSetting = docService.findDocSetting(split[i]);
                String docOrgPath = docSetting.getDocOrgPath();
                mdPath.add(docOrgPath);
                String enName = docSetting.getEnName();
                mdPath.add(enName);
                continue;
            }
            if (i == 2 && ignore && i != split.length - 1) {
                continue;
            }
            mdPath.add(split[i]);
        }
        renderFile(DocsifyConfig.defaultPath + File.separator + DocsifyConfig.gitDefaultFolderName
                + File.separator + StringUtils.join(mdPath, "/"));
    }

    @ActionKey("/docs/organizations")
    public void organizations() {
        SysUser user = getAttr("user");
        String userId = String.valueOf(user.getId());
        List<Organization> organizations = organizationService.findByUserId(userId);
        Resp.success(organizations).done(this);
    }

    @ActionKey("/docs/organizations/save")
    public void organizationsSave() {
        String reqData = getRawData();
        Organization organization = JsonKit.parse(reqData, Organization.class);
        SysUser user = getAttr("user");
        organization.setUserId(user.getId());
        boolean saveFlag = organizationService.saveOrUpdate(organization);
        Resp.resp(saveFlag).done(this);
    }

    @ActionKey("/docs/organizations/find")
    public void organizationsFind() {
        String id = getPara(0);
        Organization organization = organizationService.findById(id);
        Resp.success(organization).done(this);
    }
}